package org.sction.manager.mail;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * 简单邮件（不带附件的邮件）发送器
 */
public class MailSender {

	/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 * @throws MessagingException
	 */
	public void sendMail(final MailSenderInfo mailInfo)
			throws MessagingException {
		// 判断是否需要身份认证
		Properties pro = mailInfo.getProperties();
		// 如果需要身份认证，则创建一个密码验证器
		Session sendMailSession = null;
		if (mailInfo.isValidate()) {
			sendMailSession = Session.getInstance(pro, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(mailInfo.getUserName(),
							mailInfo.getPassword());
				}
			});
		} else {
			sendMailSession = Session.getInstance(pro, null);
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session

		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		String fromAddress = mailInfo.getFromAddress();
		if (fromAddress == null || fromAddress.trim().equals("")) {
			fromAddress = mailInfo.getUserName();
		}
		Address from = new InternetAddress(fromAddress);
		if (mailInfo.getFromName() != null) {
			try {
				from = new InternetAddress(mailInfo.getFromAddress(),
						mailInfo.getFromName());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);
		// 创建邮件的接收者地址，并设置到邮件消息中
		Address[] to = InternetAddress.parse(mailInfo.getToAddress());
		// Message.RecipientType.TO属性表示接收者的类型为TO
		mailMessage.setRecipients(Message.RecipientType.TO, to);
		if (mailInfo.getCcAddress() != null) {
			// 抄送
			Address[] cc = InternetAddress.parse(mailInfo.getCcAddress());
			mailMessage.setRecipients(Message.RecipientType.CC, cc);
		}
		if (mailInfo.getBccAddress() != null) {
			// 暗送
			Address[] bcc = InternetAddress.parse(mailInfo.getBccAddress());
			mailMessage.setRecipients(Message.RecipientType.BCC, bcc);
		}
		// 设置邮件消息的主题
		mailMessage.setSubject(mailInfo.getSubject());
		// 设置邮件消息发送的时间
		mailMessage.setSentDate(new Date());
		// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		// 设置HTML内容
		html.setContent(mailInfo.getContent(),
				"text/html; charset=" + mailInfo.getCharSet());
		mainPart.addBodyPart(html);

		if (mailInfo.getAttachFiles() != null) {
			Set<String> attachFiles = mailInfo.getAttachFiles();
			for (String path : attachFiles) {
				BodyPart attachFile = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(path);
				DataHandler dh = new DataHandler(fds);
				String fname = "";
				int index = path.lastIndexOf("\\");
				if (index == -1) {
					index = path.lastIndexOf("/");
					fname = path.substring(index);// 提取文件名
				} else {
					fname = path.substring(index + 1);// 提取文件名
				}
				try {
					fname = new String(fname.getBytes("gb2312"), "ISO8859-1");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}// 处理文件名是中文的情况
				attachFile.setFileName(fname);// 可以和原文件名不一致,但最好一样
				attachFile.setDataHandler(dh);
				mainPart.addBodyPart(attachFile);
			}
		}

		// try {
		// //设置信件的附件3(用远程文件作为附件)
		// BodyPart fj3=new MimeBodyPart();
		//
		// String url="";
		// URL urlfj = new URL(url);
		// URLDataSource ur=new URLDataSource(urlfj);
		// //注:这里用的参数只能为URL对象,不能为URL字串,在前面类介绍时有误(请谅解),这里纠正一下.
		// dh=new DataHandler(ur);
		// int ttt=url.lastIndexOf("/");
		// String urlname=url.substring(ttt);
		// //String urlfname=new
		// String(urlname.getBytes("gb2312"),"ISO8859-1");//不知怎么回事,这里不能处理中文问题
		// fj3.setFileName(urlname);
		// fj3.setDataHandler(dh);
		// mainPart.addBodyPart(fj3);
		// } catch (MalformedURLException e) {
		// e.printStackTrace();
		// }
		//
		// BodyPart fj = new MimeBodyPart();
		// DataHandler dh = new DataHandler("内容附件",
		// "text/plain;charset=gb2312");
		// // 新建一个DataHandler对象,并设置其内容和格式/编码方式
		// fj.setFileName("text.txt");// 加上这句将作为附件发送,否则将作为信件的文本内容
		// fj.setDataHandler(dh);// 给BodyPart对象设置内容为dh
		// mainPart.addBodyPart(fj);// 将含有附件的BodyPart加入到MimeMultipart对象中

		// 将MiniMultipart对象设置为邮件内容
		mailMessage.setContent(mainPart);
		// 发送邮件
		Transport.send(mailMessage, mailMessage.getAllRecipients());
	}
}
